package org.dreamland.infrastructure.persistence.typehandler

import org.apache.ibatis.type.BaseTypeHandler
import org.apache.ibatis.type.JdbcType
import org.dreamland.common.Gender
import java.sql.CallableStatement
import java.sql.PreparedStatement
import java.sql.ResultSet

class GenderTypeHandler : BaseTypeHandler<Gender>() {
    override fun setNonNullParameter(ps: PreparedStatement?, i: Int, parameter: Gender?, jdbcType: JdbcType?) {
        ps?.setInt(i, parameter?.getValue() ?: 0);
    }

    override fun getNullableResult(rs: ResultSet?, columnName: String?): Gender {
        val gender = rs?.getInt(columnName)
        return if(Gender.MALE.ofValue(gender))
            Gender.MALE
        else
            Gender.FEMAL
    }

    override fun getNullableResult(rs: ResultSet?, columnIndex: Int): Gender {
        val gender = rs?.getInt(columnIndex)
        return if(Gender.MALE.ofValue(gender))
            Gender.MALE
        else
            Gender.FEMAL
    }

    override fun getNullableResult(cs: CallableStatement?, columnIndex: Int): Gender {
        val gender = cs?.getInt(columnIndex)
        return if(gender == 0)
            Gender.MALE
        else
            Gender.FEMAL
    }
}